package com.huyirong.aicode.core;

import com.huyirong.aicode.ai.AiCodeGeneratorService;
import com.huyirong.aicode.ai.model.HtmlCodeResult;
import com.huyirong.aicode.ai.model.MultiFileCodeResult;
import com.huyirong.aicode.exception.BusinessException;
import com.huyirong.aicode.exception.ErrorCode;
import com.huyirong.aicode.model.enums.CodeGenTypeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.io.File;

//代码生成门面类，整合调用ai生成和保存功能

@Service
@Slf4j
public class AiCodeGeneratorFacade {

    @Resource
    private AiCodeGeneratorService aiCodeGeneratorService;

    /**
     *
     * @param userMessage 用户提示词
     * @param codeGenTypeEnum 生成类型
     * @return
     */
    public File generateAndSaveCode(String userMessage , CodeGenTypeEnum codeGenTypeEnum){
         if(codeGenTypeEnum == null){
             throw new BusinessException(ErrorCode.PARAMS_ERROR, "生成类型不能为空");
             //throw new RuntimeException("生成类型不能为空");
         }
         return switch (codeGenTypeEnum){
             case HTML -> generatorHtmlCode(userMessage);
             case MULTI_FILE -> generatorMultiFileCode(userMessage);
             default -> {
                 String errorMessage = "不支持生成的类型：" + codeGenTypeEnum.getValue();
                 throw new BusinessException(ErrorCode.PARAMS_ERROR, errorMessage);
             }
         };
    }

    /**
     *
     * @param userMessage 用户提示词
     * @param codeGenTypeEnum 生成类型
     * @return
     */
    public Flux<String> generateAndSaveCodeStream(String userMessage , CodeGenTypeEnum codeGenTypeEnum){
        if(codeGenTypeEnum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "生成类型不能为空");
            //throw new RuntimeException("生成类型不能为空");
        }
        return switch (codeGenTypeEnum){
            case HTML -> generatorHtmlCodeStream(userMessage);
            case MULTI_FILE -> generatorMultiFileCodeStream(userMessage);
            default -> {
                String errorMessage = "不支持生成的类型：" + codeGenTypeEnum.getValue();
                throw new BusinessException(ErrorCode.PARAMS_ERROR, errorMessage);
            }
        };
    }

    /**
     *生成代码并保存
     * @param userMessage
     * @return
     */
    private File generatorHtmlCode(String userMessage ){
        HtmlCodeResult htmlCodeResult = aiCodeGeneratorService.generatorHtmlCode(userMessage);
        return CodeFileSaver.saveHtmlResult(htmlCodeResult);
    }

    /**
     *生成多文件代码并保存
     * @param userMessage
     * @return
     */
    private File generatorMultiFileCode(String userMessage ){
        MultiFileCodeResult multiFileCodeResult = aiCodeGeneratorService.generatorMultiFileCode(userMessage);
        return CodeFileSaver.saveMultiFileCodeResult(multiFileCodeResult);
    }

    /**
     * 流式
     * @param userMessage
     * @return
     */
    private Flux<String> generatorHtmlCodeStream(String userMessage ){
        Flux<String> result =  aiCodeGeneratorService.generatorHtmlCodeStream(userMessage);
        //定义拼接器，保存所有流式代码
        StringBuilder codeBuilder = new StringBuilder();
        return result.doOnNext(chunk ->{
            //实时收集代码块
            codeBuilder.append(chunk);
        }).doOnComplete( () ->{
            try{
                String completeHtmlCode = codeBuilder.toString();
                //解析代码
                HtmlCodeResult htmlCodeResult = CodeParser.parseHtmlCode(completeHtmlCode);
                File saveDir = CodeFileSaver.saveHtmlResult(htmlCodeResult);
                log.info("保存成功，目录为：" , saveDir.getAbsolutePath());
            } catch (Exception e) {
                log.error("保存失败：{}" , e.getMessage());
            }


        });
    }

    /**
     * 流式
     * @param userMessage
     * @return
     */
    private Flux<String> generatorMultiFileCodeStream(String userMessage) {
        Flux<String> result = aiCodeGeneratorService.generatorMultiFileCodeStream(userMessage);
        StringBuilder codeBuilder = new StringBuilder();
        return result.doOnNext(chunk -> {
            // 实时拼接代码块
            codeBuilder.append(chunk);
        }).doOnComplete(() -> {
            try {
                String completeMultiFileCode = codeBuilder.toString();
                // 解析多文件代码结果
                MultiFileCodeResult multiFileCodeResult = CodeParser.parseMultiFileCode(completeMultiFileCode);
                File saveDir = CodeFileSaver.saveMultiFileCodeResult(multiFileCodeResult);
                log.info("保存成功，目录为：", saveDir.getAbsolutePath());
            } catch (Exception e) {
                log.error("保存失败：{}", e.getMessage());
            }
        });
    }

}
